<?php
App::uses('AppController', 'Controller');
/**
 * Blogs Controller
 *
 * @property Blog $Blog
 * @property PaginatorComponent $Paginator
 */
class BlogsController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator','Session');
        public $helpers = array('Form', 'Html', 'Js', 'Time','Session');

/**
 * index method
 *
 * @return void
 */
         public function beforeFilter() {
      
        $this->Auth->allow('display', 'index','view','bloglist','blogview', 'add', 'edit');
        $this->layout = 'default';
         Controller::loadModel('Menu');
         $this->set('menus', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'0'), 'order' => array('Menu.order' => 'asc'))));
         $this->set('menusbottom', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'1'), 'order' => array('Menu.order' => 'asc'))));
          $this->set('menusleft', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'2'), 'order' => array('Menu.order' => 'asc'))));
         Controller::loadModel('Category');
         Controller::loadModel('Location');
        $nodelist = $this->Category->generateTreeList(null,null,null," - ");

//			$this->set('parents',$this->Category->generatetreelist());
        $this->set('parents',($nodelist));
        $categories = $this->Category->find('list');
        $locations = $this->Location->find('list');
        $this->set(compact('locations'));
        $this->set('params','');
        
        Controller::loadModel('Paid_ads');
        $myDate = date("Y-m-d");
        // Left Ads
        $leftads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 2, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftbanners', $leftads);

        // Right Ads
        $rightads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 3, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightbanners', $rightads);

        // Top Header Ads
        $topheaderads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 4, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topheaderads', $topheaderads);

        // Top Header Ads
        $bannerads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 5, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bannerads', $bannerads);

        // Top Content Ads
        $topcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 6, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topcontentads', $topcontentads);

        // Top Content Ads
        $middlecontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 7, 'Paid_ads.expired >=' => $myDate))));
        $this->set('middlecontentads', $middlecontentads);

        // Top Content Ads
        $bottomcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 8, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bottomcontentads', $bottomcontentads);
        
        // Left Sidebar Ads
        $leftsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 9, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftsidebarads', $leftsidebarads);
        
        // Right Sidebar Ads
        $rightsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 10, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightsidebarads', $rightsidebarads);
        
        Controller::loadModel('Product');
        if($this->Session->check('order')){
           $data = $this->Session->read('order');
            $favoriteproduct = $this->Product->find('all', array('conditions' => array('Product.id' => $data)));
            $this->set('favoriteproducts', $favoriteproduct);
        }
    }
    public function bloglist(){
        $this->layout = 'home';
        $this->Blog->recursive = 0;
	$this->set('blogs', $this->Paginator->paginate());
    }

    public function index() {
            $this->layout = 'default';
		$this->Blog->recursive = 0;
		$this->set('blogs', $this->Paginator->paginate());
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function blogview($id = null) {
            $this->layout = 'home';
		if (!$this->Blog->exists($id)) {
			throw new NotFoundException(__('Invalid blog'));
		}
		$options = array('conditions' => array('Blog.' . $this->Blog->primaryKey => $id));
		$this->set('blog', $this->Blog->find('first', $options));
	}
	public function view($id = null) {
		if (!$this->Blog->exists($id)) {
			throw new NotFoundException(__('Invalid blog'));
		}
		$options = array('conditions' => array('Blog.' . $this->Blog->primaryKey => $id));
		$this->set('blog', $this->Blog->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
            
             if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
		if ($this->request->is('post')) {
			$this->Blog->create();
                        
                        $validate = true;
                        $allowedMime = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/jpg');

                        // Control Picture of Before
                        $requestimage = $this->request->data['Blog']['image'];

                        if (!empty($requestimage['type']) && in_array($requestimage['type'], $allowedMime)) {
                            $newfilename = date("YmdGis") . $requestimage['name'];
                            if (!move_uploaded_file($requestimage['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename)) {
                                $this->Blog->invalidate('image', 'File was not uploaded, please try again.');
                                $validate = false;
                            } else {
                                $this->request->data['Blog']['image'] = $newfilename;
                            }
                            //indicate which file to resize (can be any type jpg/png/gif/etc...)
                            $file = 'img/uploads/'.$newfilename;

                            //indicate the path and name for the new resized file
                            $resizedFile = 'img/uploads/images_resize/'.$newfilename;
                            $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                        } else {
                            if (!empty($requestimage['tmp_name'])) {
                                $this->Blog->invalidate('image', 'Please supply a valid image (.jpg, .gif or .png)');
                                $validate = false;
                            } else {
                                $this->request->data['Blog']['image'] = NULL;
                            }
                        }
                        
			if ($validate && $this->Blog->saveAssociated($this->request->data)) {
				$this->Session->setFlash(__('The blog has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The blog could not be saved. Please, try again.'));
			}
		}
		$users = $this->Blog->User->find('list');
		$this->set(compact('users'));
             }
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
            
        $this->Blog->id = $id;
        if (!$this->Blog->exists()) {
            throw new NotFoundException(__('Invalid product'));
        }

        if ($this->request->is('post') || $this->request->is('put')) {
            $blog = $this->Blog->find('all', array('recursive' => 1, 'conditions' => array(
                    "Blog.id" => $id))
            );
            $filename = $blog[0]['Blog']['image'];
            // For upload image
            $validate = true;
            $boolean = true;
            $allowedMime = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/jpg');

            // Control Picture of Before
            $requestimage = $this->request->data['Blog']['image'];
                if (!empty($requestimage['type']) && in_array($requestimage['type'], $allowedMime)) {
                    $newfilename = date("YmdGis") . $requestimage['name'];
                    if (!move_uploaded_file($requestimage['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename)) {
                        $this->Blog->invalidate('image', 'File was not uploaded, please try again.');
                        $validate = false;
                    } else {
                        $this->request->data['Blog']['image'] = $newfilename;
                        //indicate which file to resize (can be any type jpg/png/gif/etc...)
                        $file = 'img/uploads/'.$newfilename;

                        //indicate the path and name for the new resized file
                        $resizedFile = 'img/uploads/images_resize/'.$newfilename;
                        $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                    }
                } else {
                    if (!empty($requestimage['tmp_name'])) {
                        $this->Blog->invalidate('image', 'Please supply a valid image (.jpg, .gif or .png)');
                        $validate = false;
                    } else {
                        $this->request->data['Blog']['image'] = $filename;
                        $boolean = false;
                    }
                }
            //=======
            
            // Delete image previous image
            $imgdelete = '';
            
            if($boolean) {
                if ($filename) {
                    $file = WWW_ROOT . 'img' . DS . 'uploads' . DS . $filename;
                    if (file_exists($file)) {
                        if (unlink($file)) {
                            $imgdelete = 'and image';
                        }
                    }

                    $file = WWW_ROOT . 'img' . DS . 'uploads' . DS . 'images_resize' . DS . $filename;
                    if (file_exists($file)) {
                        if (unlink($file)) {
                            $imgdelete = 'and image';
                        }
                    }
                }
            }
            
            // Save updated product
            if ($validate && $this->Blog->saveAssociated($this->request->data)) {
                $this->Session->setFlash(__('The image has been saved'));
                $this->redirect(array('controller' => 'blogs', 'action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
            }
        }else {
                $options = array('conditions' => array('Blog.' . $this->Blog->primaryKey => $id));
                $this->request->data = $this->Blog->find('first', $options);
        }
        $users = $this->Blog->User->find('list');
        $this->set(compact('users'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
             if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
		$this->Blog->id = $id;
		if (!$this->Blog->exists()) {
			throw new NotFoundException(__('Invalid blog'));
		}
		$this->request->onlyAllow('post', 'delete');
                $deleteBlog = $this->Blog->find('all', array('conditions'=>array('Blog.id'=>$id)));
		if ($this->Blog->delete()) {
                        $picture1 = new File(WWW_ROOT ."/img/uploads/images_resize/".$deleteBlog[0]['Blog']['image']);
                        $picture1->delete();
                        $picture1 = new File(WWW_ROOT ."/img/uploads/".$deleteBlog[0]['Blog']['image']);
                        $picture1->delete();
			$this->Session->setFlash(__('The blog has been deleted.'));
		} else {
			$this->Session->setFlash(__('The blog could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}
        }
        
        
        /**
 * resize image method
 *
 * @throws NotFoundException
 * 
 * 
 */
public function smart_resize_image($file,
                              $width              = 0, 
                              $height             = 0, 
                              $proportional       = false, 
                              $output             = 'file', 
                              $delete_original    = true, 
                              $use_linux_commands = false,
  							  $quality = 100
  		 ) {
      
    if ( $height <= 0 && $width <= 0 ) return false;

    # Setting defaults and meta
    $info                         = getimagesize($file);
    $image                        = '';
    $final_width                  = 0;
    $final_height                 = 0;
    list($width_old, $height_old) = $info;
	$cropHeight = $cropWidth = 0;

    # Calculating proportionality
    if ($proportional) {
      if      ($width  == 0)  $factor = $height/$height_old;
      elseif  ($height == 0)  $factor = $width/$width_old;
      else                    $factor = min( $width / $width_old, $height / $height_old );

      $final_width  = round( $width_old * $factor );
      $final_height = round( $height_old * $factor );
    }
    else {
      $final_width = ( $width <= 0 ) ? $width_old : $width;
      $final_height = ( $height <= 0 ) ? $height_old : $height;
	  $widthX = $width_old / $width;
	  $heightX = $height_old / $height;

	  $x = min($widthX, $heightX);
	  $cropWidth = ($width_old - $width * $x) / 2;
	  $cropHeight = ($height_old - $height * $x) / 2;
    }

    # Loading image to memory according to type
    switch ( $info[2] ) {
      case IMAGETYPE_JPEG:  $image = imagecreatefromjpeg($file);  break;
      case IMAGETYPE_GIF:   $image = imagecreatefromgif($file);   break;
      case IMAGETYPE_PNG:   $image = imagecreatefrompng($file);   break;
      default: return false;
    }
    
    
    # This is the resizing/resampling/transparency-preserving magic
    $image_resized = imagecreatetruecolor( $final_width, $final_height );
    if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
      $transparency = imagecolortransparent($image);
      $palletsize = imagecolorstotal($image);

      if ($transparency >= 0 && $transparency < $palletsize) {
        $transparent_color  = imagecolorsforindex($image, $transparency);
        $transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
        imagefill($image_resized, 0, 0, $transparency);
        imagecolortransparent($image_resized, $transparency);
      }
      elseif ($info[2] == IMAGETYPE_PNG) {
        imagealphablending($image_resized, false);
        $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
        imagefill($image_resized, 0, 0, $color);
        imagesavealpha($image_resized, true);
      }
    }
    imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);


    # Taking care of original, if needed
    if ( $delete_original ) {
      if ( $use_linux_commands ) exec('rm '.$file);
      else @unlink($file);
    }

    # Preparing a method of providing result
    switch ( strtolower($output) ) {
      case 'browser':
        $mime = image_type_to_mime_type($info[2]);
        header("Content-type: $mime");
        $output = NULL;
      break;
      case 'file':
        $output = $file;
      break;
      case 'return':
        return $image_resized;
      break;
      default:
      break;
    }
    
    # Writing image according to type to the output destination and image quality
    switch ( $info[2] ) {
      case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
      case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
      case IMAGETYPE_PNG:
        $quality = 9 - (int)((0.9*$quality)/10.0);
        imagepng($image_resized, $output, $quality);
        break;
      default: return false;
    }

    return true;
  }
}
